/*
Disclaimer of Warranty: THE PACKAGE IS PROVIDED
BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS'
AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
THE IMPLIED WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT
ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW.
UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF
THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


(c) Copyright 2013 Edward Principe
All Rights Reserved

*/
#include "stdafx.h"
#include "parse.h"

////////////////////////////////////////////////////////////////
// Next: Parses next word
////////////////////////////////////////////////////////////////
TokErr Parse::Next()
{
	// Locals
	bool is_first = true; // First time thru parse loop

	// Erase word
	_word.erase(_word.begin(), _word.end());

	// Reset string flag
	_is_string = false;

	// Return if at end
	if (_is_end)
		return(TERR_NONE);

	// Go thru white spaces
	while (*_i <= ' ')
	{
		// At end?
		if (_i == _buffer.end())
		{
			_is_end = true;
			return TERR_NONE;
		}

		// Is it a comment
		if (*_i == _comment)
		{
			_is_end = true;
			return TERR_NONE;
		}

		// Go to next character
		_i++;
	}

	// Is it a string?
	if (*_i == '\"')
	{
		_is_string = true;
		_i++;
	}

	// Parser loop
	while (true)
	{
		// At end?
		if (_i == _buffer.end())
		{
			_is_end = true;
			return _is_string ? TERR_BAD_STRING : TERR_NONE;
		}

		// A comment?
		if (!_is_string && *_i == _comment)
		{
			_is_end = true;
			return TERR_NONE;
		}

		// A white space?
		if (!_is_string && *_i <= ' ')
			return TERR_NONE;

		// A string deliminator
		if (*_i == '\"')
		{
			_i++;
			return _is_string ? TERR_NONE : TERR_BAD_STRING;
		}

		// Check for deliminators
		if (!_is_string)
		{
			for (wstring::iterator i = _delim.begin(); i != _delim.end(); i++)
			{
				if (*i == *_i)
				{
					// First time thru?
					if (is_first)
					{
						_word += *_i;
						_i++;
					}

					return TERR_NONE;
				}
			}
		}

		// Get character
		is_first = false;
		_word += *_i;
		_i++;
	}
}